import {Form, Input, DatePicker, Radio, Button, Cascader, Select} from 'antd';
import React, {Component} from 'react';
import {connect} from 'react-redux';
import * as actions from '../../action/index';
import formItemLayout from '../../constant/formItemLayout';
import options from '../../constant/cityData';
import moment from 'moment';
import {FormattedMessage} from "react-intl";
import locales from "../../locales";
import {getLangFromLocalStorage} from "../../constant/lang-util";
import {withRouter} from "react-router-dom";

const {MonthPicker} = DatePicker;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const FormItem = Form.Item;

const MAINLAND_PHONE_REG = /^1(3|4|5|7|8|9)\d{9}$/
const HONGKANG_PHONE_REG = /^([5|6|8|9])\d{7}$/

class UserDetailEditor extends Component {

    state = {
        areaCode: '86'
    }

    handleSubmitClick = (e) => {
        const {currentOrganizationId} = this.props.user
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
                if (!err) {
                    let userDetails = Object.assign(values, {
                        schoolProvince: values.schoolProvince[0],
                        schoolCity: values.schoolProvince[1]
                    });
                    userDetails.currentOrganizationId = userDetails.currentOrganizationId  || currentOrganizationId
                    this.props.submitUserDetail(userDetails)
                }
            }
        );
    };
    parseLocale = (langData) =>{
        let result
        if (options) {
            result = options.map(province => {
                let children
                if (province.children) {
                    children = province.children.map(city => {
                        return Object.assign({}, city, {label : langData[city.label]})
                    })
                }
                return Object.assign({}, province, {label : langData[province.label]}, {children})
            });
        }

        return result
    }

    additionalOption = (localeOptions) =>{
        localeOptions.push({label:'other', value:'other'})
        return localeOptions
    }

    checkMobilePhone = (rule, value, callback) => {
        if(!value){
            return callback()
        }
        if (this.isHongKang()) {
            return HONGKANG_PHONE_REG.test(value) ? callback() : callback(true)
        }
        return MAINLAND_PHONE_REG.test(value) ? callback() : callback(true)
    }

    isHongKang = () => {
        return this.state.areaCode === '852'
    }

    handleAreaCodeChange = (areaCode) => {
        this.setState({areaCode})
    }

    render = () => {
        const langData = locales[getLangFromLocalStorage()].intlMessage
        let localeOptions = this.parseLocale(langData)
        localeOptions = this.additionalOption(localeOptions)
        const {organizations} = this.props
        const {getFieldDecorator} = this.props.form;
        const prefixSelector = getFieldDecorator('prefix', {
            initialValue: '86',
        })(
            <Select style={{width: 80}} onChange={this.handleAreaCodeChange}>
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
                <Option value="852">+852</Option>
            </Select>
        )

        return (

            <Form>
                <FormItem {...formItemLayout}
                          label={<FormattedMessage id='用户名' />}>
                    {this.props.user.userName }
                </FormItem>

                <FormItem {...formItemLayout}
                          label={<FormattedMessage id='邮箱' />}>
                    {this.props.user.email}
                </FormItem>



                <FormItem
                    {...formItemLayout}
                    label={(<span><FormattedMessage id='电话'/></span>)}
                >
                    {getFieldDecorator('mobilePhone', {initialValue: this.props.user.mobilePhone,
                        rules: [{
                            message: 'Incorrect format of mobile phone number.',
                            validator: this.checkMobilePhone,
                            whitespace: false
                        }],
                    })(
                        <Input addonBefore={prefixSelector} style={{width: '100%'}} type='number'/>
                    )}
                </FormItem>
              {
                organizations.length > 1?
                <FormItem {...formItemLayout}
                          label={<FormattedMessage id='当前组织' />}>
                  {getFieldDecorator('currentOrganizationId', {initialValue: this.props.user.currentOrganizationId})
                  (
                  <Select >
                    {organizations.map(organization => {
                      return <Option key={organization.id}
                                     value={organization.id}>
                        {organization.title}
                      </Option>
                    })}
                  </Select>
                  )}
                </FormItem>:''
              }
                <FormItem {...formItemLayout} label={<FormattedMessage id='姓名' />}>
                    {getFieldDecorator('name', {initialValue: this.props.user.name,
                        rules: [{required: true, message: <FormattedMessage id='请输入用户名' />}],
                    })(
                        <Input />
                    )}
                </FormItem>

                <FormItem
                    {...formItemLayout}
                    label={<FormattedMessage id='性别' />}>
                    {getFieldDecorator('gender', {initialValue: this.props.user.gender,
                        rules: [{required: true, message: <FormattedMessage id='请选择性别!' />}],
                    })(
                        <RadioGroup >
                            <Radio value={"M"}><FormattedMessage id='男' /></Radio>
                            <Radio value={"F"}><FormattedMessage id='女' /></Radio>
                        </RadioGroup>
                    )}
                </FormItem>

                <FormItem
                    {...formItemLayout}
                    label={<FormattedMessage id='学历学位' />}>
                    {getFieldDecorator('degree', {initialValue: this.props.user.degree,
                        rules: [{required: true, message: <FormattedMessage id='请选择学历!' />}],
                    })(
                        <Select >
                            <Option value="专科"><FormattedMessage id='专科及以下' /></Option>
                            <Option value="本科"><FormattedMessage id='本科' /></Option>
                            <Option value="硕士"><FormattedMessage id='硕士' /></Option>
                            <Option value="博士"><FormattedMessage id='博士' /></Option>
                        </Select>
                    )}
                </FormItem>

                <FormItem  {...formItemLayout}
                label={<FormattedMessage id='学校 / 公司' />}>
                    {getFieldDecorator('school', {initialValue: this.props.user.school,
                    rules: [{required: true, message: <FormattedMessage id='请输入学校/公司!' />}],
                })(
                <Input />
                     )}
                </FormItem>

                <FormItem
                    {...formItemLayout}
                    label={<FormattedMessage id='专业 / 职位' />}>
                    {getFieldDecorator('major', {initialValue: this.props.user.major,
                        rules: [{required: true, message: <FormattedMessage id='请输入专业/职业!' />}],
                    })(
                        <Input />
                    )}
                </FormItem>

                <FormItem  {...formItemLayout}
                           label={<FormattedMessage id='入学/职年份' />}>
                    {getFieldDecorator('entranceYear', {initialValue: this.props.user.entranceYear === null ? '' : moment(this.props.user.entranceYear),
                        rules: [{required: true, message: <FormattedMessage id='请选择入学/入职年份!' />}],
                    })(
                        <MonthPicker placeholder="Select month"/>
                    )}
                </FormItem>

                <FormItem  {...formItemLayout}
                           label={<FormattedMessage id='学校所在省市' />}>
                    {getFieldDecorator('schoolProvince', {initialValue: [`${this.props.user.schoolProvince}`, `${this.props.user.schoolCity}`],
                        rules: [{required: true, message: <FormattedMessage id='请选择学校所在的省市!' />}]})(
                        <Cascader options={localeOptions} onChange={this.onChange} placeholder="Please select"/>
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label={<FormattedMessage id='微信号' />}>
                    {getFieldDecorator('wechat', {initialValue: this.props.user.wechat
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label={<FormattedMessage id='QQ 号' />}>
                    {getFieldDecorator('qq', {initialValue: this.props.user.qq
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem>
                    <Button type="primary" htmlType="submit" onClick={this.handleSubmitClick}><FormattedMessage id='提交' /></Button>
                </FormItem>
            </Form>
        );
    }
}

const UserDetailEditorForm = Form.create()(UserDetailEditor);

const mapStateToProps = state => ({user: state.user, message: state.messages, organizations:state.organizations});

const mapDispatchToProps = dispatch => ({
    submitUserDetail: userDetail => dispatch(actions.submitUserDetail(userDetail))
});

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(UserDetailEditorForm));